package com.loong.musicdemo.ui.account.MyCenter.ui.friends;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.loong.musicdemo.R;
import com.loong.musicdemo.adapter.FriendsAdapter;
import com.loong.musicdemo.model.User;
import com.loong.musicdemo.util.dataDeal.FriendsDeal;

import java.util.ArrayList;
import java.util.List;

public class Follows extends Fragment {
    private ProgressBar loading;//刷新
    private TextView tips;//提示
    private final List<User> users = new ArrayList<>();
    private FriendsAdapter adapter;

    public Follows() {
        // Required empty public constructor
    }


    static Follows newInstance() {
        return new Follows();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new GetFollowes().execute();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_follows, container, false);
        RecyclerView recyclerViewFriends = root.findViewById(R.id.friends);
        loading = root.findViewById(R.id.loading);
        tips = root.findViewById(R.id.tips);
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        recyclerViewFriends.setLayoutManager(layoutManager);
        adapter = new FriendsAdapter(users, 2);
        recyclerViewFriends.setAdapter(adapter);
        return root;
    }

    @SuppressLint("StaticFieldLeak")
    class GetFollowes extends AsyncTask<Void, Void, List<User>> {
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            loading.setVisibility(View.VISIBLE);
        }

        @Override
        protected List<User> doInBackground(Void... voids) {
            SharedPreferences userInfo = requireActivity().getSharedPreferences("userInfo", Context.MODE_PRIVATE);
            String userId = userInfo.getString("userId", null);
            return FriendsDeal.getFollowers(userId);
        }

        @Override
        protected void onPostExecute(List<User> user) {
            super.onPostExecute(user);
            //关注列表
            if (user == null || user.size() == 0) {
                tips.setVisibility(View.VISIBLE);
            } else {
                users.addAll(user);
                adapter.notifyDataSetChanged();//刷新数据
            }
            loading.setVisibility(View.GONE);//隐藏刷新
        }
    }
}
